package chapter02.part01;

import chapter02.Employee;
import chapter02.FileUtil;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.Scanner;

/**
 * 以文本格式存储对象
 * 
 * 把 Employee 数组写入一个文本文件
 * 一行一条记录
 * 实例字段之间用 "|" 分隔
 * 
 * 每次读入一行 并分离
 * 
 * @author insight
 * @since 2021/8/13
 */
public class WriteObjectToText {
    public static void main(String[] args) {
        Employee[] staff = new Employee[3];

        staff[1] = new Employee("mugen",75000,1987,12, 15) ;
        staff[0] = new Employee("jin",60000,1986,10,1) ;
        staff[2] = new Employee("fuu", 40000,1990,3,15) ;
        
        try (PrintWriter out = new PrintWriter(FileUtil.TEST_FILE_PATH,
                StandardCharsets.UTF_8)) {
            writeData(out, staff);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (Scanner in = new Scanner(
                FileUtil.getTestFileInputStreamInstance(), StandardCharsets.UTF_8)) {
            Employee[] employees = readData(in);

            for (Employee e : employees) {
                System.out.println(e);
            }
        }
    }

    public static void writeData(PrintWriter out, Employee[] employees) {
        out.println(employees.length);

        for (Employee e : employees) {
            writeEmployee(out, e);
        }
    }

    public static Employee[] readData(Scanner in) {
        int len = in.nextInt();
        // 读取回车
        in.nextLine();

        Employee[] employees = new Employee[len];
        for (int i = 0; i < employees.length; i++) {
            employees[i] = readEmployee(in);
        }
        
        return employees;
    }
    
    public static void writeEmployee(PrintWriter out, Employee e) {
        out.println(e.getName() + "|" + e.getSalary() + "|" + e.getHireDay());
    }

    public static Employee readEmployee(Scanner in) {
        String line = in.nextLine();
        // | 需要使用 \ 转义 而 \ 本身也需要转义
        String[] tokens = line.split("\\|");
        String name = tokens[0];
        double salary = Double.parseDouble(tokens[1]);
        LocalDate date = LocalDate.parse(tokens[2]);
        int year = date.getYear();
        int month = date.getMonthValue();
        int day = date.getDayOfMonth();
        
        return new Employee(name, salary, year, month, day);
    }
}